package comcksys.authserver.service.impl;

import comcksys.authserver.entity.User;
import comcksys.authserver.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义获取用户
 * @author: yxzhang23
 * @time: 2021/4/8
 */
@Component
public class MyUserDetailsServerImpl implements UserDetailsService {

    private final IUserService userService;

    @Autowired
    public MyUserDetailsServerImpl(IUserService userService) {
        this.userService = userService;
    }

    /**
     * 通过用户名加载用户
     * @param s 用户名
     * @return  用户Details信息
     * @throws UsernameNotFoundException 未找到该用户
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userService.getUserByUsername(s);
        List<SimpleGrantedAuthority> authorities = user.getRoles().stream()
                .map(t -> new SimpleGrantedAuthority(t.getName())).collect(Collectors.toList());

        return new MyUserDetailsImpl(user.getUsername(), user.getPassword(), authorities);
    }
}
